package com.sample.fileupload;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;

@ManagedBean(name="fileuploadcontroller")
@RequestScoped
public class FileUploadController {

    public void uploadAttachment(FileUploadEvent event) {
        UploadedFile file = event.getFile();
        ExternalContext ec = FacesContext.getCurrentInstance().getExternalContext();
        String txtField = ec.getRequestParameterMap().get("myform:txtField");
        String filePath = ec.getRealPath(String.format("/resources/img/%s", file.getFileName()));
        try {
            FileOutputStream fos = new FileOutputStream(filePath);
            fos.write(file.getContents());
            fos.flush();
            fos.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        FacesContext context = FacesContext.getCurrentInstance();
        context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, String.format("Archivo cargado: %s ", file.getFileName()),
                String.format("Mensaje: %s", txtField)));

    }

}
